package cn.yunhe.test;

import cn.yunhe.entity.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.Serializable;

public class Demo1 implements Serializable {
    Session session = null;
    Transaction tr = null;
    @Before
    public void init(){
        Configuration cfg =  new  Configuration().configure(); //获得Hibernate配置管理接口
       SessionFactory factory = cfg.buildSessionFactory();  //根据Configuration实例创建session的工厂类SessionFactory
       session= factory.openSession();   //通过session工厂获得session实例
    }



    @Test
    public void test(){//新增加
        tr= session.beginTransaction();//开启事务
        Person person = new Person();
        person.setId(2);
        person.setUsername("zhangsan2");
        person.setUserpassword("123454");
        person.setAge(13);
        session.save(person);   //保存
        tr.commit();  //提交事务
    }
    @Test
    public void update(){//修改
        tr= session.beginTransaction();//开启事务
        Person person = (Person) session.get(Person.class,2);
        person.setAge(18);
        session.update(person);
        tr.commit();
    }
    @Test
    public void sel(){//查询
        Person person = (Person) session.get(Person.class,2);
        System.out.println("id:"+person.getId());
        System.out.println("getUsername:"+person.getUsername());
        System.out.println("getUserpassword:"+person.getUserpassword());
        System.out.println("getAge:"+person.getAge());
    }
    @Test
    public void del(){
        tr = session.beginTransaction();
        Person person = (Person) session.get(Person.class,1);
        session.delete(person);
        tr.commit();
    }
    @Test
    public void saveorupt(){//新增或修改
        tr=session.beginTransaction();
        Person person = new Person(4,"lisi","123456",16);
        session.saveOrUpdate(person);

        tr.commit();  //提交事务
    }
    @After
    public void destory(){
        session.close();
    }
}
